'use client'
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';

import BlogCard,{ type BlogPost } from '@/components/BlogCard';
import Sidebar from '../components/Sidebar';
import { Category } from '@/types/category';
import { Tag } from '@/types/tag';
import { type Article } from '@/types/article';
import { getArticles, getPopularArticles } from '../services/articleService';
import { getPopularTags } from '../services/tagService';
import { ChevronDown } from 'lucide-react';
import { useAppContext } from '../components/AppLayout';
import EditButton from '../components/EditButton';


// 类型转换函数：将Article转换为BlogCard需要的格式
const convertToBlogPost = (article: Article): BlogPost => {
  // 获取分类名称
  const getCategoryName = (): string => {
    try {
      const categoriesJson = localStorage.getItem('categories');
      if (categoriesJson) {
        const categories = JSON.parse(categoriesJson);
        const matchedCategory = categories.find((cat: Category) => cat.id === article.categoryId);
        return matchedCategory?.name || '未分类';
      }
    } catch (error) {
      // 静默失败，返回默认值
    }
    return '未分类';
  };

  // 提取文章摘要
  const getExcerpt = (): string => {
    if (article.excerpt) return article.excerpt;
    if (article.content) return article.content.substring(0, 150) + '...';
    return '';
  };

  // 默认图片URL
  const defaultImageUrl = 'https://images.unsplash.com/photo-1581091226825-a6a2a5aee158?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixlib=rb-1.2.1&q=80&w=1080';

  return {
    id: article.id,
    title: article.title,
    excerpt: getExcerpt(),
    author: article.author?.username || '未知作者',
    date: new Date(article.createdAt).toISOString().split('T')[0],
    category: getCategoryName(),
    tags: article.tags?.map(tag => tag.name) || [],
    image: article.coverImage || defaultImageUrl,
    readTime: Math.ceil((article.content?.length || 0) / 500) + '分钟阅读',
    viewCount: article.viewCount || 0,
    likeCount: article.likeCount || 0,
  };
};


export default function HomePage() {
  const router = useRouter();
  const { currentCategory, searchQuery, setSearchQuery } = useAppContext(); // 从Context获取共享状态
  const [articles, setArticles] = useState<Article[]>([]);// 文章列表
  const [popularPosts, setPopularPosts] = useState<any[]>([]);// 热门文章
  const [tags, setTags] = useState<Tag[]>([]);// 热门标签
  const [loading, setLoading] = useState(true);// 是否正在加载文章列表
  const [loadingMore, setLoadingMore] = useState(false);// 是否正在加载更多文章
  const [page, setPage] = useState(1);// 当前页码
  const [totalPages, setTotalPages] = useState(1);// 总页数
  const [hasMore, setHasMore] = useState(true); // 是否还有更多文章可以加载
  
  // 搜索文章 - 只在按回车时触发
  const handleSearch = (query: string) => {
    setSearchQuery(query);
    // 重置分页
    setPage(1);
    setHasMore(true);
    setArticles([]);
    // 立即触发文章加载，包括搜索框清空的情况
    fetchArticles(1, 3, false, currentCategory, query.trim());
  };

  // 获取标签TAG并存储到localStorage
  const fetchTags = useCallback(async () => {
    try {
      // 先尝试从localStorage获取
      const cachedTags = localStorage.getItem('blog_tags');
      if (cachedTags) {
        setTags(JSON.parse(cachedTags));
        return;
      }
      
      // 从API获取并存储到localStorage
      const tagData = await getPopularTags(20);
      setTags(tagData);
      localStorage.setItem('blog_tags', JSON.stringify(tagData));
    } catch (error) {
      console.error('获取标签失败:', error);
    }
  }, []);

  // 获取热门文章
  const fetchPopularPosts = useCallback(async () => {
    try {
      const popularData = await getPopularArticles(5);
      setPopularPosts(popularData);
    } catch (error) {
      // 静默失败，保持空数组
      setPopularPosts([]);
    }
  }, []);

  // 获取文章列表
  const fetchArticles = useCallback(async (
    pageNum: number = 1,
    limit: number = 3,
    shouldAppend: boolean = false,
    category?: Category | null,
    search?: string
  ) => {
    shouldAppend ? setLoadingMore(true) : setLoading(true);
    
    try {
      // 构建请求参数
      const params: Record<string, any> = { page: pageNum, limit };
      
      // 添加分类筛选
      if (category && 'id' in category) {
        params.categoryId = category.id;
      }
      
      // 添加搜索筛选
      const searchText = search || searchQuery.trim();
      if (searchText) {
        params.search = searchText;
      }
      
      const response = await getArticles(params);
      
      // 更新文章列表
      if (shouldAppend) {
        setArticles(prev => [...prev, ...response.data]);
      } else {
        setArticles(response.data);
      }
      
      // 更新分页信息
      setTotalPages(response.totalPages);
      setHasMore(pageNum < response.totalPages);
      setPage(pageNum);
    } catch (error) {
      // 错误处理
      if (!shouldAppend) {
        setArticles([]);
      }
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  }, [searchQuery]);

  // 初始加载数据：只加载一次标签和热门文章
  useEffect(() => {
    fetchTags();
    fetchPopularPosts();
  }, [fetchTags, fetchPopularPosts]);
  
  // 文章加载逻辑：只在分类变化时触发
  useEffect(() => {
    // 设置状态重置
    setPage(1);
    setHasMore(true);
    
    // 立即触发文章加载，使用当前搜索查询
    fetchArticles(1, 3, false, currentCategory, searchQuery.trim());
  }, [currentCategory, fetchArticles]); // 只监听分类变化

  // 转换文章数据为BlogCard需要的格式
  const blogPosts = articles.map(convertToBlogPost);
  
  //加载更多函数
  const handleLoadMore = useCallback(() => {
    if (!loadingMore && hasMore) {
      fetchArticles(page + 1, 3, true, currentCategory);
    }
  }, [fetchArticles, loadingMore, hasMore, page, currentCategory]);

  // 处理文章点击，导航到文章详情页
  const handlePostClick = (postId: number) => {
    router.push(`/article/${String(postId)}`);
  };

  // 热门文章点击复用同一个处理函数
  const handlePopularPostClick = handlePostClick;

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2">
          <div className="mb-6">
            <h1 className="text-gray-900">
              {currentCategory ? `${currentCategory.name} 分类文章` : '最新文章'}
            </h1>
            <p className="text-gray-600 mt-2">
              {blogPosts.length} 篇文章
            </p>
          </div>
          
          {loading ? (
            <div className="text-center py-12">
              <div className="w-8 h-8 border-4 border-gray-200 border-t-blue-500 rounded-full animate-spin mx-auto mb-2"></div>
              <p className="text-gray-500">加载中...</p>
            </div>
          ) : blogPosts.length > 0 ? (
            <div className="grid gap-6">
              {blogPosts.map((post) => (
                <BlogCard
                  key={post.id}
                  post={post}
                  onClick={() => handlePostClick(post.id)}
                />
              ))}
              {/* 加载更多按钮 */}
              <div className="py-8 text-center">
                {loadingMore && (
                  <div className="flex flex-col items-center justify-center">
                    <div className="w-8 h-8 border-4 border-gray-200 border-t-blue-500 rounded-full animate-spin mb-2"></div>
                    <p className="text-gray-500">加载中...</p>
                  </div>
                )}
                {hasMore && !loadingMore && (
                  <div className="relative flex items-center justify-center py-8">
                    <div className="absolute inset-0 flex items-center">
                      <div className="h-px w-full bg-gray-200"></div>
                    </div>
                    <a 
                      href="#" 
                      onClick={(e) => {
                        e.preventDefault();
                        handleLoadMore();
                      }}
                      className="relative px-8 py-1 text-gray-600 text-xs hover:text-blue-600 hover:underline transition-colors duration-300 focus:outline-none"
                    >
                      加载更多
                      <ChevronDown 
                        className="inline-block w-3 h-3 ml-1 transition-transform hover:translate-y-0.5"
                      />
                    </a>
                  </div>
                )}
                {!hasMore && articles.length > 0 && !loadingMore && (
                  <p className="text-gray-500">已经到底了，没有更多文章了</p>
                )}
              </div>
            </div>
          ) : (
            <div className="text-center py-12">
              <p className="text-gray-500">没有找到符合条件的文章</p>
            </div>
          )}
        </div>

        <div className="lg:col-span-1">
          <Sidebar 
            popularPosts={popularPosts} 
            tags={tags} 
            onBack={() => {}}
            onPostClick={handlePopularPostClick}
          />
        </div>
      </div>
      <EditButton className="bottom-16" />
    </div>
  );
}
